//
//  AssortViewController.m
//  Cat
//
//  Created by lushitong on 2018/11/29.
//  Copyright © 2018年 lushitong. All rights reserved.
//

#import "AssortViewController.h"
#import "LeftTableViewCell.h"
#import "LJCollectionViewFlowLayout.h"
#import "CollectionViewCell.h"
#import "HttpAssottManager.h"
#import "ClassViewController.h"

static float kLeftTableViewWidth = 93.0f;
static float kCollectionViewMargin = 3.f;

@interface AssortViewController ()<UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegateFlowLayout,UICollectionViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) NSMutableArray *collectionDatas;
@property (nonatomic, strong) LJCollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) NSMutableArray *sorrtModelArray;
@property (nonatomic, strong) NSMutableArray *categoryArray;

@end

@implementation AssortViewController {
	NSInteger _selectIndex;
	BOOL _isScrollDown;
}

- (void)viewDidLoad {
    [super viewDidLoad];
	[self.topTitleView setDetailDic:@{Nav_Title:@"分类"}.mutableCopy];
	self.topTitleView.backgroundColor = COLOR_WITH_HEX(0xFFC236);
	self.topTitleView.bottomLineView.backgroundColor = [UIColor whiteColor];
	self.edgesForExtendedLayout = UIRectEdgeNone;
	self.extendedLayoutIncludesOpaqueBars = NO;
	self.automaticallyAdjustsScrollViewInsets = NO;
	
	[self.view addSubview:self.tableView];
	[self.view addSubview:self.collectionView];
	
	[self.tableView reloadData];
	[self.collectionView reloadData];
	[self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]
								animated:YES
						  scrollPosition:UITableViewScrollPositionNone];
	[self requestData];
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
}

- (void)requestData {
	[HttpAssottManager getCategoryListWithSuccess:^(AssortCategroyModel *assort) {
		self.sorrtModelArray = assort.categoryList.mutableCopy;
		CategoryInfo *cateModel = assort.categoryList.firstObject;
		[self requestThisItemWithCategoryID:cateModel.categoryID];
		dispatch_async(dispatch_get_main_queue(), ^{
			[self.tableView reloadData];
			[self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]
										animated:YES
								  scrollPosition:UITableViewScrollPositionNone];
		});
	} failure:^(NSInteger code, NSString * _Nonnull message) {
		[FLProgressHUD showError:message];
	}];
}

- (void)requestThisItemWithCategoryID:(NSNumber *)categoryID {
	[HttpAssottManager getCategoryListWithProductListWithCategoryID:categoryID WithSuccess:^(AssortCategroyModel *assort) {
		self.categoryArray = assort.categoryList.mutableCopy;
		dispatch_async(dispatch_get_main_queue(), ^{
			[self.collectionView reloadData];
		});
	} failure:^(NSInteger code, NSString * _Nonnull message) {
		[FLProgressHUD showError:message];
	}];
	
}

#pragma mark - UITableView DataSource Delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
	return self.sorrtModelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	LeftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LeftTableViewCell" forIndexPath:indexPath];
	CategoryInfo *model = [self.sorrtModelArray safeObjectAtIndex:indexPath.row];
	cell.name.text = model.name;
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
	_selectIndex = indexPath.row;
	CategoryInfo *cateModel = [self.sorrtModelArray safeObjectAtIndex:indexPath.row];
	[self requestThisItemWithCategoryID:cateModel.categoryID];
	[self scrollToTopOfSection:_selectIndex animated:YES];
	[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:_selectIndex inSection:0]
						  atScrollPosition:UITableViewScrollPositionTop animated:YES];
}


- (void)scrollToTopOfSection:(NSInteger)section animated:(BOOL)animated {
	CGRect headerRect = [self frameForHeaderForSection:section];
	CGPoint topOfHeader = CGPointMake(0, headerRect.origin.y - _collectionView.contentInset.top);
	[self.collectionView setContentOffset:topOfHeader animated:animated];
}

- (CGRect)frameForHeaderForSection:(NSInteger)section {
	NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:section];
	UICollectionViewLayoutAttributes *attributes = [self.collectionView.collectionViewLayout layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader atIndexPath:indexPath];
	return attributes.frame;
}

#pragma mark - UICollectionView DataSource Delegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
	return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
	return self.categoryArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
	CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([CollectionViewCell class]) forIndexPath:indexPath];
	CategoryInfo *cateModel = [self.categoryArray safeObjectAtIndex:indexPath.row];
	[cell setInfoModel:cateModel];
	return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView
				  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
	CGFloat width = (ScreenWidth - kLeftTableViewWidth - 4 * kCollectionViewMargin) / 3;
	return CGSizeMake(width, width + kQKFitModuleDecimal(20));
}

// CollectionView分区标题即将展示
- (void)collectionView:(UICollectionView *)collectionView willDisplaySupplementaryView:(UICollectionReusableView *)view forElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath {
	// 当前CollectionView滚动的方向向上，CollectionView是用户拖拽而产生滚动的（主要是判断CollectionView是用户拖拽而滚动的，还是点击TableView而滚动的）
	if (!_isScrollDown && (collectionView.dragging || collectionView.decelerating))
	{
		[self selectRowAtIndexPath:indexPath.section];
	}
}

// CollectionView分区标题展示结束
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingSupplementaryView:(nonnull UICollectionReusableView *)view forElementOfKind:(nonnull NSString *)elementKind atIndexPath:(nonnull NSIndexPath *)indexPath {
	// 当前CollectionView滚动的方向向下，CollectionView是用户拖拽而产生滚动的（主要是判断CollectionView是用户拖拽而滚动的，还是点击TableView而滚动的）
	if (_isScrollDown && (collectionView.dragging || collectionView.decelerating)) {
		[self selectRowAtIndexPath:indexPath.section + 1];
	}
}

// 当拖动CollectionView的时候，处理TableView
- (void)selectRowAtIndexPath:(NSInteger)index {
	[self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
	[collectionView deselectItemAtIndexPath:indexPath animated:YES];
	CategoryInfo *cateModel = [self.categoryArray safeObjectAtIndex:indexPath.row];
	ClassViewController *clasVC  = [[ClassViewController alloc] init];
	clasVC.titileString = cateModel.name;
	clasVC.productNumber = cateModel.categoryID;
	[self.navigationController pushViewController:clasVC animated:YES];
}

#pragma mark - UIScrollView Delegate
// 标记一下CollectionView的滚动方向，是向上还是向下
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
	static float lastOffsetY = 0;
	if (self.collectionView == scrollView){
		_isScrollDown = lastOffsetY < scrollView.contentOffset.y;
		lastOffsetY = scrollView.contentOffset.y;
	}
}

#pragma mark----- lazy init -----

- (NSMutableArray *)dataSource{
	if (!_dataSource){
		_dataSource = [NSMutableArray array];
	}
	return _dataSource;
}

- (NSMutableArray *)collectionDatas {
	if (!_collectionDatas){
		_collectionDatas = [NSMutableArray array];
	}
	return _collectionDatas;
}

- (UITableView *)tableView {
	if (!_tableView){
		_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.topTitleView.bottom, kLeftTableViewWidth, ScreenHeight - NavigationBarHeight)];
		_tableView.delegate = self;
		_tableView.dataSource = self;
		_tableView.tableFooterView = [UIView new];
		_tableView.rowHeight = kQKFitModuleDecimal(50);
		_tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
		_tableView.showsVerticalScrollIndicator = NO;
		_tableView.separatorColor = [UIColor clearColor];
		[_tableView registerClass:[LeftTableViewCell class] forCellReuseIdentifier:NSStringFromClass([LeftTableViewCell class])];
	}
	return _tableView;
}

- (UICollectionView *)collectionView {
	if (!_collectionView)
	{
		_collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(kLeftTableViewWidth + kQKFitModuleDecimal(1.0), self.topTitleView.bottom, ScreenWidth - kLeftTableViewWidth - kQKFitModuleDecimal(1.0), ScreenHeight - NavigationBarHeight - kQKFitModuleDecimal(1.5)) collectionViewLayout:self.flowLayout];
		_collectionView.delegate = self;
		_collectionView.dataSource = self;
		_collectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
		_collectionView.showsVerticalScrollIndicator = NO;
		_collectionView.showsHorizontalScrollIndicator = NO;
		[_collectionView setBackgroundColor:[UIColor whiteColor]];
		//注册cell
		[_collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([CollectionViewCell class])];
	}
	return _collectionView;
}

- (LJCollectionViewFlowLayout *)flowLayout {
	if (!_flowLayout) {
		_flowLayout = [[LJCollectionViewFlowLayout alloc] init];
		_flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
		_flowLayout.minimumInteritemSpacing = 2;
		_flowLayout.minimumLineSpacing = 2;
	}
	return _flowLayout;
}

- (NSMutableArray *)sorrtModelArray {
	if (!_sorrtModelArray) {
		_sorrtModelArray = [[NSMutableArray alloc] init];
	}
	return _sorrtModelArray;
}

- (NSMutableArray *)categoryArray {
	if (!_categoryArray) {
		_categoryArray = [[NSMutableArray alloc] init];
	}
	return _categoryArray;
}

@end
